<template>
  <div class="warp">
    <div class="warp_auto">
      <div class="warp_top">
        <div class="jiansuo-box">
          <span class="label">工号：</span>
          <el-input
            v-model="gonghao"
            class="input"
            clearable
            placeholder="请输入"
          />
        </div>
        <div class="jiansuo-box">
          <span class="label">姓名：</span>
          <el-input
            v-model="xingming"
            class="input"
            clearable
            placeholder="请输入"
          />
        </div>
        <div class="jiansuo-box">
          <span class="label">性别：</span>
          <el-select
            v-model="xinbie"
            class="input"
            clearable
            placeholder="请选择"
          >
            <el-option
              v-for="item in sex"
              :key="item.id"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </div>
        <div class="jiansuo-box">
          <span class="label">角色：</span>
          <el-select
            v-model="jiaoshe"
            class="input"
            clearable
            placeholder="请选择"
          >
            <el-option
              v-for="item in roleaaa"
              :key="item.id"
              :label="item.role_name"
              :value="item.id"
            />
          </el-select>
        </div>
        <div class="jiansuo-box">
          <span class="label">用户类型：</span>
          <el-select
            v-model="liexin"
            class="input"
            clearable
            placeholder="请选择"
          >
            <el-option
              v-for="item in list_a"
              :key="item.id"
              :label="item.user_type_name"
              :value="item.user_type_code"
            />
          </el-select>
        </div>
        <div class="jiansuo-box">
          <span class="label">状态：</span>
          <el-select
            v-model="value"
            class="input"
            clearable
            placeholder="请选择"
          >
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </div>
        <div class="jiansuo-box">
          <span class="label">科室：</span>
          <el-select
            v-model="keshia"
            class="input"
            clearable
            placeholder="请选择"
            filterable
          >
            <el-option
              v-for="item in list_atl"
              :key="item.id"
              :label="item.department_name"
              :value="item.department_code"
            />
          </el-select>
        </div>
        <div class="jiansuo-box">
          <el-button
            type="primary"
            icon="el-icon-search"
            class="btn"
            @click="btn"
            >检索</el-button>
          <el-button
            class="btn"
            @click="handleOption('新增')"
          >新增</el-button>
        </div>
      </div>
      <el-card>
        <el-table
          :data="arr"
          style="width: 100%"
          height="540"
          stripe
          :header-cell-style="{ background: '#d2e0f9', color: '#606266' }"
        >
          <el-table-column label="姓名" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.user_name }}</span>
            </template>
          </el-table-column>
          <el-table-column label="工号"  align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.work_number }}</span>
            </template>
          </el-table-column>
          <el-table-column label="性别"  align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.sex === 0 ? "女" : "男" }}</span>
            </template>
          </el-table-column>
          <el-table-column
            property="status"
            label="状态"
            align="center"
            header-align="center"
          >
            <template scope="scope">
              <el-switch
                v-model="scope.row.status"
                class="switch-btn"
                inactive-text="禁用"
                active-text="启用"
                :active-value="1"
                :inactive-value="0"
                active-color="#02538C"
                inactive-color="#B9B9B9"
                @change="changeSwitchs(scope.$index, scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="用户类型" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.user_type_name }}</span>
            </template>
          </el-table-column>
          <el-table-column label="角色" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.role_name }}</span>
            </template>
          </el-table-column>
          <el-table-column label="创建时间"  align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.create_time.substring(0, 10) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="240" align="center">
            <template slot-scope="scope">
              <el-button size="mini" @click="handleOption('编辑', scope.row)"
              >编辑</el-button
              >
              <el-popover
                :ref="`popover-${scope.$index}`"
                trigger="click"
                placement="top"
                width="140"
              >
                <p class="el-icon-warning">确定删除</p>
                <div style="text-align: right; margin: 0">
                  <el-button size="mini" type="text" @click="no(scope)"
                  >取消</el-button
                  >
                  <el-button type="primary" size="mini" @click="yes(scope)"
                  >确定</el-button
                  >
                </div>
                <el-button
                  slot="reference"
                  size="mini"
                  style="margin-left: 10px"
                  type="danger"
                >删除</el-button
                >
              </el-popover>
              <el-popover
                :ref="`popoverr-${scope.$index}`"
                trigger="click"
                placement="top"
                width="140"
              >
                <p class="el-icon-warning">确认重置该用户密码吗</p>
                <div style="text-align: right; margin: 0">
                  <el-button size="mini" type="text" @click="nouild(scope)"
                  >取消</el-button
                  >
                  <el-button type="primary" size="mini" @click="rebuild(scope)"
                  >确定</el-button
                  >
                </div>
                <el-button
                  slot="reference"
                  size="mini"
                  style="margin-left: 10px"
                  type="warning"
                >重置密码</el-button
                >
              </el-popover>
            </template>
          </el-table-column>
        </el-table>
        <div class="paging">
          <el-pagination
            :current-page="start"
            :page-size="PageSize"
            :pager-count="5"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalCount"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>

    <!-- 新增、编辑用户 -->
    <el-dialog
      :title="title"
      :visible.sync="dialogFormVisible"
      :close-on-click-modal="false"
      width="600px"
    >
      <el-form
        ref="ruleForm"
        :model="userInfo"
        :rules="rules"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="工号：" prop="workNumber">
          <el-input
            v-model="userInfo.workNumber"
            class="el-inputer"
            placeholder=""
          />
        </el-form-item>
        <el-form-item label="姓名：" prop="userName">
          <el-input
            v-model="userInfo.userName"
            class="el-inputer"
            placeholder=""
          />
        </el-form-item>
        <el-form-item label="性别：" prop="sex">
          <el-radio-group v-model="userInfo.sex">
            <el-radio :label="0">女</el-radio>
            <el-radio :label="1">男</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="用户类型：" prop="userTypeCode">
          <el-select
            v-model="userInfo.userTypeCode"
            class="el-inputer"
            clearable
            placeholder="请选择"
          >
            <el-option
              v-for="item in listSelect"
              :key="item.id"
              :label="item.user_type_name"
              :value="item.user_type_code"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="角色：" prop="roleId">
          <el-select
            v-model="userInfo.roleId"
            clearable
            placeholder="请选择"
            class="el-inputer"
          >
            <el-option
              v-for="item in roleaaa"
              :key="item.id"
              :label="item.role_name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态：" prop="status">
          <el-switch
            v-model="userInfo.status"
            class="switch-btn"
            inactive-text="禁用"
            active-text="启用"
            :active-value="1"
            :inactive-value="0"
            active-color="#02538C"
            inactive-color="#B9B9B9"
          />
        </el-form-item>
<!--        <el-form-item label="上传签名：" prop="status">-->
<!--          <el-upload-->
<!--            action=""-->
<!--            :on-change="getFile"-->
<!--            :limit="1"-->
<!--            list-type="picture"-->
<!--            :auto-upload="false"-->
<!--            :file-list="fileList"-->
<!--          >-->
<!--            <el-button size="small"-->
<!--            >选择图片</el-button-->
<!--            >-->
<!--          </el-upload>-->
<!--        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="submitForm()"
        >保 存</el-button
        >
      </div>
    </el-dialog>
    <!-- switch -->
    <el-dialog title="状态更新" :visible.sync="dialogUpdata" class="mod_box1">
      <span>
        <i class="el-icon-warning" />此操作将会改变开关状态, 是否继续?</span
      >
      <span slot="footer" class="dialog-footer">
        <el-button @click="(dialogUpdata = false), cancelSwitch()"
          >取 消</el-button
        >
        <el-button
          type="primary"
          @click="(dialogUpdata = false), updataSwitch()"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {
  usergetList,
  userTypequeryList,
  rolequeryList,
  userdelete,
  resetPassword,
  userinsert,
  userupdate,
  userTypelist,
  departmentDictionaryqueryList, useredit
} from "@/api/table";
export default {
  data() {
    return {
      title: '',
      dialogUpdata: false, // 开关
      switchId: "",
      switchStatus: "",
      fileList: [],
      xinbie: "",
      jiaoshe: "",
      xingming: "",
      gonghao: "",
      liexin: "",
      keshia: "",
      role_: "",
      name: "",
      start: 1, // 默认显示第几页
      totalCount: 0, // 总条数，根据接口获取数据长度(注意：这里不能为空)
      pgeSizes: [10, 20, 30, 40], // 个数选择器（可修改）
      PageSize: 10, // 默认每页显示的条数（可修改）
      dialogFormVisible: false,
      userInfo: {
        workNumber: "",
        userName: "",
        sex: "",
        userTypeCode: "",
        roleId: "",
        status: 1,
        enterTime: "", //多余字段
        exitTime: "", //多余字段
        signImgStr: "", //多余字段
        simplicity: '' //多余字段
      },
      rules: {
        workNumber: [
          { required: true, message: "工号不能为空", trigger: "blur" },
        ],
        sex: [
          { required: true, message: "性别不能为空", trigger: "blur" },
        ],
        userTypeCode: [
          { required: true, message: "用户类型不能为空", trigger: "blur" },
        ],
        userName: [
          { required: true, message: "名称不能为空", trigger: "blur" },
        ],
        roleId: [{ required: true, message: "角色不能为空", trigger: "blur" }],
      },
      options: [
        {
          id: "0",
          value: "1",
          label: "启用",
        },
        {
          id: "1",
          value: "0",
          label: "禁用",
        },
      ],
      sex: [
        {
          id: "1",
          value: 0,
          label: "女",
        },
        {
          id: "0",
          value: 1,
          label: "男",
        },
      ],
      value: "",
      arr: [],
      listSelect: [],
      role: [],
      roleaaa: [],
      list_a: [],
      list_atl: [],
    };
  },
  mounted() {
    this.list(this.PageSize, this.start);
    userTypelist().then((res) => {
      this.list_a = res.data;
    });
    departmentDictionaryqueryList().then((res) => {
      this.list_atl = res.data;
    });
    userTypequeryList().then((res) => {
      this.listSelect = res.data;
    });
    rolequeryList().then((res) => {
      this.roleaaa = res.data;
    });
  },
  methods: {
    getBase64(file) {
      return new Promise(function (resolve, reject) {
        let reader = new FileReader();
        let imgResult = "";
        reader.readAsDataURL(file);
        reader.onload = function () {
          imgResult = reader.result;
        };
        reader.onerror = function (error) {
          reject(error);
        };
        reader.onloadend = function () {
          resolve(imgResult);
        };
      });
    },

    getFile(file, fileList) {
      this.getBase64(file.raw).then((res) => {
        this.userInfo.signImgStr = res;
      });
    },
    yes(scope) {
      // 可以在这里执行删除数据的回调操作.......删除操作......
      const id = scope.row.id;
      userdelete({ id: id }).then((res) => {
        this.list(this.PageSize, this.start);
      });

      this.$message({
        message: "删除成功",
        type: "success",
      });
      scope._self.$refs[`popover-${scope.$index}`].doClose();
    },
    // 重设密码
    rebuild(scope) {
      // 可以在这里执行删除数据的回调操作.......删除操作......
      const id = scope.row.id;
      resetPassword({ id: id }).then((res) => {
        this.list(this.PageSize, this.start);
      });

      this.$message({
        message: "密码重置成功，重置后的密码为123456！",
        type: "success",
      });
      scope._self.$refs[`popoverr-${scope.$index}`].doClose();
    },
    nouild() {
      this.$message("取消重设");
      scope._self.$refs[`popoverr-${scope.$index}`].doClose();
    },
    no(scope) {
      this.$message("取消删除");
      scope._self.$refs[`popover-${scope.$index}`].doClose();
    },
    handleOption(title, data){
      this.dialogFormVisible = true;

      this.title = title;

      if(title == '编辑'){
        this.userInfo = {
          id: data.id,
          status: data.status,
          workNumber: data.work_number,
          userName: data.user_name,
          sex: data.sex,
          userTypeCode: data.user_type_code,
          roleId: data.role_id,
          enterTime: data.enter_time,
          exitTime: data.create_time,
          simplicity: '',
          signImgStr: ''
        };
      }else{
        this.userInfo = {
          workNumber: "",
          userName: "",
          sex: "",
          userTypeCode: "",
          roleId: "",
          status: 1,
          enterTime: "",
          exitTime: "",
          signImgStr: "",
          simplicity: ''
        }
      }
    },
    // 新增or编辑
    submitForm() {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          this.dialogFormVisible = false;

          if(this.title == '新增'){
            userinsert({
              ...this.userInfo,
              loginName: this.userInfo.workNumber,
            }).then((res) => {
              this.list(this.PageSize, this.start);

              this.$message({message: res.msg, type: "info"});
            });

          }else{
            useredit({
              ...this.userInfo,
              loginName: this.userInfo.workNumber,
            }).then((res) => {
              this.list(this.PageSize, this.start);

              this.$message({message: res.msg, type: "info"});
            });
          }

        } else {
          this.$message({message: "请填写必填项！", type: "warning"});
          this.dialogFormVisible = true;
          return false;
        }
      });
    },
    // 列表开关的id
    changeSwitchs(index, row) {
      this.switchId = row.id;
      this.switchStatus = row.status;
      this.dialogUpdata = true;
    },
    // 保存开关状态-确认
    updataSwitch() {
      userupdate({
        id: this.switchId,
        status: this.switchStatus,
      }).then((res) => {
        this.btn();
      });
    },
    // 保存开关状态-取消
    cancelSwitch() {
      this.list(this.PageSize, this.start); // 重新获取表格
    },
    // 搜索按钮
    btn() {
      this.start = 1;

      this.list(this.PageSize, this.start);
    },
    list(n1, n2) {
      var deptCode="";
      if(this.keshia!=""){
        deptCode=this.keshia.replace(/\b(0+)/gi,"");
      }
      usergetList({
        userName: this.xingming,
        workNumber: this.gonghao,
        sex: this.xinbie === "" ? null : this.xinbie,
        roleId: this.jiaoshe,
        userTypeCode: this.liexin,
        deptCode: deptCode,
        status: this.value === "" ? null : this.value,
        size: n1,
        start: n2,
      }).then((res) => {
        this.arr = res.data;
        this.totalCount = res.totalCount;
      });
    },
    // 每页显示的条数
    handleSizeChange(val) {
      // 改变每页显示的条数
      this.PageSize = val;
      // 点击每页显示的条数时，显示第一页
      this.list(val, 1);
      // 注意：在改变每页显示的条数时，要将页码显示到第一页
      this.start = 1;
    },
    // 显示第几页
    handleCurrentChange(val) {
      // 改变默认的页数
      this.start = val;

      // 切换页码时，要获取每页显示的条数
      this.list(this.PageSize, (this.start = val));
    },
  },
};
</script>
